<template>
  <el-dialog v-model="visible" title="创建用户">
    <create-form @submit="createUser" @cancel="close" v-bind="attrs"></create-form>
  </el-dialog>
</template>

<script setup>
import { ref, useAttrs } from 'vue'
import CreateForm from './form.vue'
import api from '@/http/index.js'
import { ElMessage } from 'element-plus'
const visible = ref(false)
let resolvePromise = null
let rejectPromise = null
const attrs = useAttrs()

const createUser = async (data) => {
  api.user
    .post(data)
    .then(({ data = {} } = {}) => {
      // if (!data.id) throw new Error('创建用户失败')
      ElMessage({
        message: '创建用户成功',
        type: 'success',
      })
      return resolvePromise(data)
    })
    .catch(() => {
      ElMessage({
        message: '创建用户失败',
        type: 'error',
      })
      rejectPromise()
    })
    .finally(() => {
      close()
    })
}

const close = () => {
  visible.value = false
  resolvePromise()
  resolvePromise = null
  rejectPromise = null
}

const open = () => {
  visible.value = true
  resolvePromise = null
  rejectPromise = null
  return new Promise((resolve, reject) => {
    resolvePromise = resolve
    rejectPromise = reject
  })
}

defineExpose({
  open,
  close,
})
</script>

<style lang="scss"></style>
